<?php

namespace App\Exception\Handler;

use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;
use Throwable;

// 自定义全局异常
class CustomizeExceptionHandler extends ExceptionHandler
{

    protected LoggerInterface $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    public function handle(\Throwable $throwable, \Psr\Http\Message\ResponseInterface $response)
    {


        $data = [
            'code' => 500,
            'msg' => $throwable->getMessage(),
        ];

        $this->logger->error($throwable->getMessage());

        return $response->withStatus(500)->withAddedHeader('content-type', 'application/json; charset=utf-8')->withBody(new \Hyperf\HttpMessage\Stream\SwooleStream(json_encode($data)));
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}